import { defineStore } from 'pinia';
import { store } from '/@/store';
import type { CreateDeck, DeckCardItem } from '/@/api/verse/model/deckModel';
import { cloneDeep } from 'lodash-es';
import { isArray } from '/@/utils/is';

interface IState {
  createDeck: CreateDeck;
}

interface IGetter {
  getCreateDeckParams: (state: IState) => IState['createDeck'];
  [propName: string]: ((state: IState) => IState | unknown) | (() => void);
}

interface IActions {
  setCreateDeckFighter: (data: DeckCardItem | DeckCardItem[]) => void;
  setCreateDeckMainCard: (data: DeckCardItem[]) => void;
  setCreateDeckOtherCard: (data: DeckCardItem[]) => void;
  clearCreateDeckParams: () => void;
}

export const useVerseStore = defineStore<'app_verse', IState, IGetter, IActions>({
  id: 'app_verse',
  state: () => {
    return {
      createDeck: {
        deck_name: '',
        main_fighters: [],
        main_cards: [],
        other_cards: [],
      },
    };
  },

  getters: {
    getCreateDeckParams: (state) => {
      return state.createDeck;
    },
  },

  actions: {
    setCreateDeckFighter(data: DeckCardItem | DeckCardItem[]) {
      if (isArray(data)) {
        this.createDeck.main_fighters = cloneDeep(data);
        return;
      }
      // 根据card_id判断
      let delIndex = -1;
      for (let i = 0; i < this.createDeck.main_fighters.length; i++) {
        if (data.card_id === this.createDeck.main_fighters[i].card_id) {
          delIndex = i;
          break;
        }
      }
      if (delIndex >= 0) {
        this.createDeck.main_fighters.splice(delIndex, 1);
        return;
      }
      // 同一职业主战者选择一个
      delIndex = -1;
      for (let i = 0; i < this.createDeck.main_fighters.length; i++) {
        if (data.card_career === this.createDeck.main_fighters[i].card_career) {
          delIndex = i;
          break;
        }
      }
      if (delIndex >= 0) {
        this.createDeck.main_fighters.splice(delIndex, 1);
      }
      this.createDeck.main_fighters.push(data);
    },
    setCreateDeckMainCard(data) {
      this.createDeck.main_cards = cloneDeep(data);
    },
    setCreateDeckOtherCard(data) {
      this.createDeck.other_cards = cloneDeep(data);
    },
    clearCreateDeckParams() {
      this.createDeck.deck_name = '';
      this.setCreateDeckFighter([]);
      this.setCreateDeckMainCard([]);
      this.setCreateDeckOtherCard([]);
    },
  },
});

// Need to be used outside the setup
export function useVerseStoreWithOut() {
  return useVerseStore(store);
}
